<template>
  <div class="app-container">
    <div class="search-con">
      <div class="title">查询条件</div>
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="人员姓名" prop="personId">
          <el-select v-model="queryParams.personId" placeholder="请选择人员" clearable>
            <el-option v-for="person in personList" :key="person.id" :label="person.name" :value="person.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="档案名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入档案名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
            <el-option v-for="dict in record_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="发生原因" prop="etiology">
          <el-select v-model="queryParams.etiology" placeholder="请选择发生原因" clearable>
            <el-option v-for="dict in etiology" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="档案状态" prop="state">
          <el-select v-model="queryParams.state" placeholder="请选择档案状态" clearable>
            <el-option v-for="dict in health_record_state" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="发生时间" prop="time">
          <el-date-picker v-model="queryParams.time" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>
      </el-form>
      <div class="search-btn-con">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button type="info" icon="Refresh" @click="resetQuery">重置</el-button>
      </div>
    </div>
    <div class="main-con">
      <div class="title-con">
        <div class="title">基本信息</div>
        <div class="operate-btn-con">
          <el-button @click="handleAdd" icon="Plus" v-hasPermi="['health:healthRecord:add']">新增</el-button>
          <el-button :disabled="multiple" icon="Delete" @click="handleDelete" v-hasPermi="['health:healthRecord:remove']">删除</el-button>
          <!-- <el-button @click="handleExport" icon="Download" v-hasPermi="['health:healthRecord:export']">导出</el-button> -->
        </div>
      </div>
      <div class="content-con" v-loading="loading" height="calc(100% - 0.65rem)">
        <el-table v-loading="loading" :data="healthRecordList" @selection-change="handleSelectionChange" height="calc(100% - 0.65rem)">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" label="序号" :index="indexMethod" width="50"></el-table-column>
          <el-table-column label="人员姓名" align="center" width="100" prop="personName" />
          <el-table-column label="档案名称" align="center" width="160" prop="name" />
          <el-table-column label="类型" align="center" width="100" prop="type">
            <template #default="scope">
              <dict-tag :options="record_type" :value="scope.row.type" />
            </template>
          </el-table-column>
          <el-table-column label="档案状态" align="center" width="100" prop="state">
            <template #default="scope">
              <dict-tag :options="health_record_state" :value="scope.row.state" />
            </template>
          </el-table-column>
          <el-table-column label="发生时间" align="center" prop="occurTime" width="160"> </el-table-column>
          <el-table-column label="康复时间" align="center" prop="rehabilitationTime" width="160"> </el-table-column>
          <el-table-column label="康复周期" align="center" prop="duration" width="160"> </el-table-column>
          <el-table-column label="发生原因" align="center" width="120" prop="etiology">
            <template #default="scope">
              <dict-tag :options="etiology" :value="scope.row.etiology" />
            </template>
          </el-table-column>
          <el-table-column label="初期症状" align="center" prop="initialSymptoms" />
          <!-- <el-table-column label="中期症状" align="center" prop="mediumTermSymptoms" />
          <el-table-column label="后期症状" align="center" prop="laterStageSymptoms" /> -->
          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <div class="ctrl-btn d-flex">
                <el-tooltip v-for="item in operateList" :key="item.id" class="item" effect="dark" :content="item.title" placement="top">
                  <el-button :icon="item.icon" v-hasPermi="item.hasPermi" circle @click="handleOperate(item.id, scope.row)"></el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          small
          background
          layout="total,sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加或修改健康档案对话框 -->
    <el-dialog :title="title" v-model="open" width="880px" append-to-body>
      <el-form ref="healthRecordRef" :model="form" :inline="true" :rules="rules" label-width="120px">
        <el-form-item label="人员姓名" prop="personId">
          <el-select v-model="form.personId" placeholder="请选择人员" @change="handlePersonChange" clearable>
            <el-option v-for="person in personList" :key="person.id" :label="person.name" :value="person.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="档案名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入档案名称" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option v-for="dict in record_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="档案状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择档案状态">
            <el-option v-for="dict in health_record_state" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发生时间" prop="occurTime">
          <el-date-picker clearable v-model="form.occurTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择发生时间"> </el-date-picker>
        </el-form-item>
        <el-form-item label="发生原因" prop="etiology">
          <el-select v-model="form.etiology" placeholder="请选择发生原因">
            <el-option v-for="dict in etiology" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="康复时间" style="width: 792px" prop="rehabilitationTime">
          <el-date-picker clearable v-model="form.rehabilitationTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择康复时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="初期症状" style="width: 792px" prop="initialSymptoms">
          <el-input v-model="form.initialSymptoms" type="textarea" placeholder="请输入初期症状" />
        </el-form-item>

        <el-form-item label="中期症状" style="width: 792px" prop="mediumTermSymptoms">
          <el-input v-model="form.mediumTermSymptoms" type="textarea" placeholder="请输入中期症状" />
        </el-form-item>
        <el-form-item label="后期症状" style="width: 792px" prop="laterStageSymptoms">
          <el-input v-model="form.laterStageSymptoms" type="textarea" placeholder="请输入后期症状" />
        </el-form-item>

        <el-form-item label="备注" style="width: 792px" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template v-if="title !== '查看健康档案'" #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="detailTitle" v-model="detailOpen" width="1150px" append-to-body>
      <el-radio-group v-model="activeName" style="margin-bottom: 20px">
        <el-radio-button label="first">基本信息</el-radio-button>
        <el-radio-button label="second">就医记录</el-radio-button>
        <el-radio-button label="third">过程记录</el-radio-button>
        <el-radio-button label="marStatic">用药统计</el-radio-button>
        <el-radio-button label="fourth">体温记录</el-radio-button>
      </el-radio-group>
      <div v-if="activeName === 'first'" class="basic-information">
        <el-row :gutter="20">
          <el-col :span="8">
            <span class="title">人员姓名：</span><span class="content">{{ basicInformation.personName }}</span>
          </el-col>
          <el-col :span="8">
            <span class="title">档案名称：</span><span class="content">{{ basicInformation.name }}</span>
          </el-col>
          <el-col :span="8">
            <span class="title">类型：</span>
            <span class="content"><dict-tag style="display: inline" :options="record_type" :value="basicInformation.type" /></span>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <span class="title">档案状态：</span>
            <span class="content"><dict-tag style="display: inline" :options="health_record_state" :value="basicInformation.state" /></span>
          </el-col>
          <el-col :span="8">
            <span class="title">发生时间：</span><span class="content">{{ basicInformation.occurTime }}</span>
          </el-col>
          <el-col :span="8">
            <span class="title">发生原因：</span>
            <span class="content"><dict-tag style="display: inline" :options="etiology" :value="basicInformation.etiology" /></span>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <span class="title">康复时间：</span><span class="content">{{ basicInformation.rehabilitationTime }}</span>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <span class="title">初期症状：</span><span class="content">{{ basicInformation.initialSymptoms }}</span>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <span class="title">中期症状：</span><span class="content">{{ basicInformation.mediumTermSymptoms }}</span>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <span class="title">后期症状：</span><span class="content">{{ basicInformation.laterStageSymptoms }}</span>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <span class="title">备注：</span><span class="content">{{ basicInformation.remark }}</span>
          </el-col>
        </el-row>
      </div>
      <div v-if="activeName === 'second'" class="basic-information">
        <div class="main-con">
          <div class="content-con">
            <el-table v-loading="doctorRecordLoading" :data="doctorRecordList">
              <el-table-column label="医院名称" align="center" width="180" prop="hospitalName" />
              <el-table-column label="科室" align="center" width="120px" prop="departments" />
              <el-table-column label="大夫" align="center" width="100px" prop="doctor" />
              <el-table-column label="就诊时间" align="center" prop="visitingTime" width="180"> </el-table-column>
              <el-table-column label="诊断及开药" align="center" prop="prescribe" />
            </el-table>
          </div>
        </div>
      </div>
      <div v-if="activeName === 'marStatic'" class="basic-information">
        <div class="main-con">
          <div class="content-con">
            <el-table v-loading="doctorRecordLoading" :data="mar.marMapList">
              <el-table-column label="序号" width="50" type="index" align="center">
                <template #default="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="药品名称" align="center" prop="medicalName" />
              <el-table-column label="用药天数" width="150" align="center" prop="useDays" />
              <el-table-column label="用药次数" width="150" align="center" prop="count" />
              <el-table-column label="用药总量" width="150" align="center" prop="dosage" />
              <el-table-column label="单位" width="150" align="center" prop="unit" />
            </el-table>
          </div>
        </div>
      </div>
      <div v-if="activeName === 'third'" class="basic-information">
        <div class="main-con">
          <div class="content-con">
            <el-table v-loading="processRecordLoading" :data="processRecordList">
              <el-table-column label="记录时间" align="center" prop="createTime" width="180"> </el-table-column>
              <el-table-column label="记录内容" align="center" prop="content" />
            </el-table>
          </div>
        </div>
      </div>
      <div v-if="activeName === 'fourth'" class="basic-information">
        <div class="main-con">
          <div class="content-con">
            <el-table v-loading="temperatureRecordLoading" :data="temp.tableList">
              <el-table-column label="序号" width="50" type="index" align="center">
                <template #default="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="测量日期" align="center" prop="time" />
              <el-table-column label="测量次数" align="center" prop="count" />
              <el-table-column label="最高体温（℃）" align="center" prop="max" />
              <el-table-column label="最低体温（℃）" align="center" prop="min" />
              <el-table-column label="平均体温（℃" align="center" prop="average" />
              <el-table-column prop="detail" width="300" label="测量明细">
                <template #default="scope">
                  <span v-html="formatMultiLineData(scope.row.detail)"></span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <template #footer> </template>
    </el-dialog>
  </div>
</template>

<script setup name="HealthRecord">
import { listHealthRecord, getHealthRecord, delHealthRecord, addHealthRecord, updateHealthRecord } from '@/api/health/healthRecord'
import { listPerson, getPerson } from '@/api/health/person'
import { listTemperatureRecord } from '@/api/health/temperatureRecord'
import { listMarRecord } from '@/api/health/marRecord'
import { listProcessRecord } from '@/api/health/processRecord'
import { getMarAnalysis, getTemperatureAnalysis } from '@/api/health/statisticAnalysis'
import { listDoctorRecord } from '@/api/health/doctorRecord'
import dayjs from 'dayjs'
// eslint-disable-next-line no-unused-vars
import { require } from '@/utils/require'
import { nextTick, reactive, toRefs } from 'vue'
const { proxy } = getCurrentInstance()
const { record_type, etiology, health_record_state } = proxy.useDict('record_type', 'etiology', 'health_record_state')
const healthRecordList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const personList = ref([])

const detailTitle = ref('')
const detailOpen = ref(false)
const basicInformation = ref(null)
const activeName = ref('first')
const currentId = ref('')
const marRecordLoading = ref(false)
const marRecordList = ref([])
const marTotal = ref(0)
const mar = ref({})

const temperatureRecordLoading = ref(false)
const temperatureRecordList = ref([])
const tempTotal = ref(0)
const temp = ref({})

const doctorRecordLoading = ref(false)
const doctorRecordList = ref([])

const processRecordLoading = ref(false)
const processRecordList = ref([])

const operateList = ref([
  { id: 'view', icon: 'View', title: '查看', hasPermi: ['health:healthRecord:query'] },
  { id: 'edit', icon: 'Edit', title: '修改', hasPermi: ['health:healthRecord:edit'] },
  { id: 'delete', icon: 'Delete', title: '删除', hasPermi: ['health:healthRecord:remove'] }
])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    type: null,
    time: '',
    etiology: null,
    personId: null,
    state: null
  },
  queryMarRecordParams: {
    pageNum: 1,
    pageSize: 100,
    healthRecordId: null
  },
  queryDoctorRecordParams: {
    pageNum: 1,
    pageSize: 100,
    healthRecordId: null
  },
  queryTemperatureRecordParams: {
    pageNum: 1,
    pageSize: 100,
    healthRecordId: null
  },
  queryPersonParams: {
    pageNum: 1,
    pageSize: 1000
  },
  rules: {
    name: [{ required: true, message: '档案名称不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '类型不能为空', trigger: 'change' }],
    occurTime: [{ required: true, message: '发生时间不能为空', trigger: 'blur' }],
    initialSymptoms: [{ required: true, message: '初期症状不能为空', trigger: 'blur' }],
    etiology: [{ required: true, message: '发生原因不能为空', trigger: 'blur' }],
    personId: [{ required: true, message: '人员姓名不能为空', trigger: 'blur' }],
    state: [{ required: true, message: '档案状态不能为空', trigger: 'blur' }]
  }
})

function formatMultiLineData(data) {
  if (data != null) {
    return data.replace(/<br\/>/g, '<br/>')
  }
}
const handleOperate = (operate, row) => {
  switch (operate) {
    case 'view':
      handleView(row)
      break
    case 'edit':
      handleUpdate(row)
      break
    case 'delete':
      handleDelete(row)
      break
    default:
      break
  }
}

const { queryParams, form, rules, queryPersonParams, queryMarRecordParams, queryTemperatureRecordParams, queryDoctorRecordParams } = toRefs(data)

const handlePersonChange = (personId) => {
  getPerson(personId).then((response) => {
    const date = new Date()
    const year = date.getFullYear() // 年份
    let month = date.getMonth() + 1 // 月份，返回值为0-11，所以需要加1
    let day = date.getDate() // 日期

    // 对月份和日期进行补零
    month = month < 10 ? '0' + month : month.toString()
    day = day < 10 ? '0' + day : day.toString()

    const currentDate = year + month + day
    form.value.name = response.data.name + currentDate + '档案'
  })
}

/** 查询健康档案列表 */
function getList() {
  loading.value = true
  const timeRange = queryParams.value.time
  let st = ''
  let et = ''
  if (timeRange && timeRange.length === 2) {
    st = dayjs(timeRange[0]).format('YYYY-MM-DD')
    et = dayjs(timeRange[1]).format('YYYY-MM-DD')
  }
  queryParams.value.startTime = st
  queryParams.value.endTime = et
  listHealthRecord(queryParams.value).then((response) => {
    healthRecordList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
/** 查询成员管理列表 */
function getPersonList() {
  listPerson(queryPersonParams.value).then((response) => {
    personList.value = response.rows
  })
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    type: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    occurTime: null,
    rehabilitationTime: null,
    initialSymptoms: null,
    mediumTermSymptoms: null,
    laterStageSymptoms: null,
    etiology: null,
    personId: null,
    state: '1'
  }
  proxy.resetForm('healthRecordRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}
// 分页
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

//每页显示条数改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}
// 序号翻页递增
const indexMethod = (index) => {
  const nowPage = queryParams.value.pageNum //当前第几页，根据组件取值即可
  const nowLimit = queryParams.value.pageSize //当前每页显示几条，根据组件取值即可
  return index + 1 + (nowPage - 1) * nowLimit // 这里可以理解成一个公式
}
// 分页
const handleTempCurrentChange = (val) => {
  queryTemperatureRecordParams.value.pageNum = val
  // 体温记录
  listTemperatureRecord(queryTemperatureRecordParams.value).then((res) => {
    temperatureRecordList.value = res.rows
    tempTotal.value = res.total
  })
}

// 分页
const handleMarCurrentChange = (val) => {
  queryMarRecordParams.value.pageNum = val
  // 用药记录
  listMarRecord(queryMarRecordParams.value).then((res) => {
    marRecordList.value = res.rows
    marTotal.value = res.total
  })
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 查看
const handleView = (row) => {
  const _id = row.id || ids.value
  currentId.value = _id
  activeName.value = 'first'
  getHealthRecord(_id).then((response) => {
    basicInformation.value = response.data
    detailOpen.value = true
    detailTitle.value = '查看健康档案'
  })
  queryMarRecordParams.value.healthRecordId = _id
  queryTemperatureRecordParams.value.healthRecordId = _id
  queryDoctorRecordParams.value.healthRecordId = _id
  // 体温记录
  listTemperatureRecord(queryMarRecordParams.value).then((res) => {
    temperatureRecordList.value = res.rows
    tempTotal.value = res.total
  })
  //用药记录
  listMarRecord(queryMarRecordParams.value).then((res) => {
    marRecordList.value = res.rows
    marTotal.value = res.total
  })
  getMarAnalysis({ recordId: _id, dataType: '1', type: 1 }).then((response) => {
    loading.value = false
    mar.value = { ...response.data }
  })

  getTemperatureAnalysis({ recordId: _id, dataType: '1', type: 1 }).then((response) => {
    loading.value = false
    temp.value = { ...response.data }
  })
  // 就医记录
  listDoctorRecord(queryDoctorRecordParams.value).then((res) => {
    doctorRecordList.value = res.rows
  })
  // 过程记录
  listProcessRecord(queryDoctorRecordParams.value).then((res) => {
    processRecordList.value = res.rows
  })
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加健康档案'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getHealthRecord(_id).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改健康档案'
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs.healthRecordRef.validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateHealthRecord(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addHealthRecord(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delHealthRecord(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'health/healthRecord/export',
    {
      ...queryParams.value
    },
    `healthRecord_${new Date().getTime()}.xlsx`
  )
}

getList()
getPersonList()
</script>
